#include <ACUASlcd.h>

uint8_t lcd_waitbusy(void);
uint8_t lcd_read(uint8_t rs);

/// Global char array to hold the value of a number to be displayed as a string on the LCD
/// @see LCD_NUMBER(), LCD_D_NUMBER()
char lcd_str[21];

void LCDcharDef( uint8_t n,
						uint8_t row8,
						uint8_t row7,
						uint8_t row6,
						uint8_t row5,
						uint8_t row4,
						uint8_t row3,
						uint8_t row2, 
						uint8_t row1)
{
	uint8_t i,m=(n-1)*8;

	lcd_command(_BV(LCD_CGRAM));

	for(i=0;i<m;i++)
	{
		lcd_waitbusy();
		lcd_read(1);
	}
	lcd_data(row8);
	lcd_data(row7);
	lcd_data(row6);
	lcd_data(row5);
	lcd_data(row4);
	lcd_data(row3);
	lcd_data(row2);
	lcd_data(row1);
}

void LCDbargraphV(long int yv, long int ymin, long int ymax, long int posx)
{
	long int y;

	y = yv - ymin;
	y = y * 160;
	y = (y / (ymax - ymin) + 5) / 10;

	if(y>8) 
	{
		LCD_XY(posx,1) LCD_CHAR(y-8-1)
		LCD_XY(posx,2) LCD_CHAR(8-1)
	}
	else if(y>0)
	{
		LCD_XY(posx,1) LCD_CHAR(' ')
		LCD_XY(posx,2) LCD_CHAR(y-1)
	}
	else
	{
		LCD_XY(posx,1) LCD_CHAR(' ')
		LCD_XY(posx,2) LCD_CHAR(' ')
		}
}

void assert_lcd(const char * function, const char * file, int line, const char * expression)
{
	lcd_init(LCD_DISP_ON);
	lcd_clrscr();
	lcd_puts(expression); lcd_putc('|');
	lcd_puts(function); lcd_putc('|');
	lcd_puts(file); lcd_putc('(');
	itoa(line,lcd_str,10); lcd_puts(lcd_str);lcd_putc(')');
	
	// Reset the device by watchdog
	for(int i=0; i<ASSERT_WAIT_SECS; i++) 
	{
		LCD_XY(15,2) LCD_CHAR('B') LCD_D_NUMBER(ASSERT_CONFIRM_BUTTON,1,0) WAIT_SEC(0.5) // Display button number
		LCD_XY(15,2) LCD_D_NUMBER(ASSERT_WAIT_SECS-i,2,0) WAIT_SEC(0.5)   // Display remaining seconds
		if(!(PINA & (1 << (ASSERT_CONFIRM_BUTTON-1))))                    // If button pressed
		{
			while(!(PINA & (1 << (ASSERT_CONFIRM_BUTTON-1))));            // Wait for release button
			while(1)                                                      // Wait forever
				if(!(PINA & (1 << (ASSERT_CONFIRM_BUTTON-1)))) break;     // If button pressed again, leave the while-loop
		}
		if(!(PINA & (1 << (ASSERT_CONFIRM_BUTTON-1)))) break;             // Leave the for-loop, too
				
	}
	wdt_enable(WDTO_30MS); while(1) {}                                    // reset the device
}